package org.goobs.chess;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HumanChessAgent implements ChessAgent{

	private int color;
	
	public HumanChessAgent(int color){
		this.color = color;
	}
	
	@Override
	public ChessMove decideMove(ChessPosition pos) {
		String sInput = null;
		while(sInput == null){
			//(try getting a move)
			String input = ChessGame.console.readLine("move?");
//			try {
//				input = new BufferedReader(new InputStreamReader(System.in)).readLine();
//			} catch (IOException e1) {
//				System.out.println("Could not get keyboard");
//				try {
//					Thread.sleep(1000);
//				} catch (InterruptedException e) {}
//				continue;
//			}
			//(sanitize the move)
			try {
				sInput = sanitize(input);
			} catch (IllegalArgumentException e) {
				ChessGame.console.println("Could not decode move: " + input);
				continue;
			}
			ChessMove candidate = ChessMove.decode(sInput);
			//(check if the move is valid)
			ChessPosition afterMove = pos.move(candidate);
			if( !pos.calculateInformation(color).getChildren().contains(afterMove) ){
				ChessGame.console.println("Not a valid chess move: " + sInput);
				sInput = null;
				continue;
			}
			System.out.println("here2");
		}
		System.out.println("here");
		return ChessMove.decode(sInput);
	}

	@Override
	public int getColor() {
		return color;
	}

	@Override
	public boolean claimsVictory() {
		return false;
	}
	
	private static final String sanitize(String move) throws IllegalArgumentException{
		if(move == null || move.equals("")){
			throw new IllegalArgumentException("No move given");
		}
		
		//--Precise regex
		Pattern p = Pattern.compile("([a-h]|[A-H])[1-8]-[a-h][1-8]");
		Matcher m = p.matcher(move);
		if(m.find()){
			//(Standard form)
			String rtn = m.group();
			rtn = rtn.toLowerCase();
			return rtn;
		}
		
		return null;
	}

}
